<template>
  <div class="goods-recharge">
    <loading v-if="isloading"></loading>
    <div v-else>
      <cell-group>
        <field v-if="orderNumber" v-model="balance" label-width="100px" label="当前余额：" readonly />
        <field v-if="orderNumber" v-model="goodsMoney" label-width="100px" label="当前货款：" readonly />

        <field v-if="orderNumber" v-model="orderNumber" label-width="100px" label="订单编号：" readonly />
        <field
          v-if="orderNumber"
          v-model="orderDetail.orderInfo.dealTime"
          label-width="100px"
          label="下单时间："
          readonly
        />

        <!-- <field v-if="false" v-model="selectedPayType.name" label-width="100px" label="打款方式：" readonly right-icon="arrow-down" @click="popupType = 'payType', showPopup = true"/>
      <field v-if="false && selectedPayType.id == 2" v-model="bankName" label-width="100px" label="银行名称：" placeholder="请输入银行名称" />
      <field v-if="false && selectedPayType.id == 2" v-model="accountName" label-width="100px" label="开户实名：" placeholder="请输入开户实名" />
      <field v-if="false && selectedPayType.id == 2" v-model="account" label-width="100px" label="银行卡账号：" type="number" placeholder="请输入你的银行卡账号" />
        <field v-if="false && selectedPayType.id == 1" v-model="account" label-width="100px" label="支付宝账号：" placeholder="请输入你的支付宝账号" />-->

        <field
          v-if="orderNumber"
          :value="'￥'+orderDetail.orderInfo.orderMoney"
          label-width="100px"
          label="订单金额："
          placeholder="请输入打款金额"
          type="string"
          readonly
        />
        <!-- <field v-else v-model="payMoney" label-width="100px" label="金额：" placeholder="请输入打款金额" type='number'/> -->

        <!-- @click="popupType = 'date', showPopup = true" -->
        <!-- <field v-model="time" label-width="100px" label="打款日期：" readonly right-icon="arrow-down" /> -->

        <!-- <field v-if="false" v-model="remark" label-width="100px" label="备注：" placeholder="如有说明可填写备注" /> -->

        <!-- <div class="upload-proof" v-if="false">
        <div class="upload-proof-text">打款凭证<br>(1-2张)：</div>
        <uploader :max-count="2" v-model="payImgList" :after-read="afterRead" />
        </div>-->
      </cell-group>

      <!-- <pay-info v-if="!orderNumber"></pay-info> -->

      <div class="submit">
        <van-button
          type="info"
          size="large"
          @click="recharge"
          :disabled="isSubmitting"
        >{{isSubmitting ? '正在提交' : '确认支付'}}</van-button>
      </div>
    </div>

    <!-- <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'payType'">
        <picker
          @cancel="onCancel"
          value-key="name"
          show-toolbar
          :columns="payTypeList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'date'">
        <datetime-picker
          v-model="currentDate"
          type="date"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="onConfirm"
          @cancel="onCancel"
        />
      </div>
    </popup>-->
  </div>
</template>

<script>
import {
  Field,
  Cell,
  CellGroup,
  Uploader,
  Button,
  Picker,
  Toast,
  DatetimePicker
} from "vant";
import payInfo from "../components/pay_info.vue";
import popup from "../components/popup.vue";
var moment = require("moment");
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
import loading from "../components/loading.vue";

export default {
  components: {
    Field,
    Cell,
    CellGroup,
    Uploader,
    vanButton: Button,
    payInfo,
    popup,
    Picker,
    DatetimePicker,
    loading
  },
  data() {
    return {
      isloading: true,
      goodsMoney: "",
      balance: "",
      agentInfo: {},
      orderDetail: {
        orderInfo: {}
      },
      orderNumber: this.$route.query.orderNumber || "",
      showPopup: false,
      selectedPayType: {
        id: 1,
        name: "支付宝"
      },
      payTypeList: [
        {
          id: 1,
          name: "支付宝"
        },
        {
          id: 2,
          name: "银行转账"
        }
      ],
      agencyLevelList: [
        {
          id: 0,
          level_name: "全部"
        }
      ],
      selectedAgencyLevel: {
        id: 0,
        level_name: "全部"
      },
      popupType: "",
      account: "",
      // bankName: "",
      // accountName: "",
      payMoney: "",
      remark: "",
      payImgList: [],
      time: moment(new Date()).format("YYYY年MM月DD日"),
      currentDate: new Date(),
      isSubmitting: false
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  async mounted() {
    if (this.orderNumber) {
      let data = {
        title: "订单支付"
      };
      this.$store.commit("setNavInfo", data);
      document.title = data.title + " - TIMELESS 分销商城";

      await this.getAgentInfo();
      await this.getOrderDetail();
    }

    this.isloading = false
  },
  methods: {
    // 从订单详情跳过来时 根据订单号获取订单信息
    getOrderDetail() {
      return this.$http
        .post(this.$urls.GJDDHHQ, {
          orderNum: this.orderNumber
        })
        .then(res => {
          if (res.data.code == 200) {
            this.orderDetail = res.data.data;
          }
        });
    },

    // 货款充值  订单支付
    recharge() {
      // if (
      //   Number(this.orderDetail.orderInfo.orderMoney) >
      //     Number(this.agentInfo.goods_money) ||
      //   Number(this.orderDetail.orderInfo.orderMoney) >
      //     Number(this.agentInfo.balance)
      // ) {
      //   Toast("余额和货款都不足以支付订单金额");
      //   return false;
      // }

      let applyInfo = {
        // account: this.account,
        payMoney: Number(this.payMoney),
        remark: this.remark,
        // payImage: this.payImgList.length ? [...this.payImgList].map(item => item.content) : "",
        // handDocuments: [...this.handImgList].map(item => item.content),
        // agentLevel: this.selectedAgencyLevel.id,
        payType: this.selectedPayType.id,
        payTime: moment(this.currentDate).format("YYYY-MM-DD"),
        applyType: 3
      };

      // 未支付订单货款支付时
      if (this.orderNumber) {
        applyInfo = Object.assign({}, applyInfo, {
          payMoney: this.orderDetail.orderInfo.orderMoney,
          orderNum: this.orderNumber
        });
      }

      let verify = {
        payMoney: "金额",
        account: "账户"
        // payImage: "打款凭证"
        // handDocuments: "手持证"
      };

      // 打款方式为 银行卡时
      // if(this.selectedPayType.id == 2){
      //   applyInfo = Object.assign({}, applyInfo, {
      //     bankName: this.bankName,
      //     accountName: this.accountName
      //   })

      //   verify = Object.assign({}, verify, {
      //     bankName: '银行名称',
      //     accountName: '开户名称'
      //   })
      // }

      for (let item in applyInfo) {
        if (!applyInfo[item]) {
          if (item in verify) {
            // console.log(item);
            Toast(verify[item] + "不能为空");
            return false;
          }
        }
      }

      // console.log(applyInfo)
      Toast("正在提交，请稍候");
      // this.isSubmitting = true;
      // return false;

      this.$http.post(this.$urls.QZFDD, {
        orderId: this.orderDetail.orderInfo.id
      }).then(res => {
        this.isSubmitting = false;
        if (res.data.code == 200) {
          let data = res.data.data;

          Toast.success("支付订单成功");
          this.$router.go(-1);
          resolve();
        } else {
          Toast(res.data.msg);
        }
      });
    },
    getAgentInfo() {
      return http
        .post(urls.DLXQ, {
          id: this.userInfo.id
        })
        .then(res => {
          if (res.data.code == 200) {
            let data = res.data.data;
            this.agentInfo = data;

            this.goodsMoney = "￥" + this.agentInfo.goods_money;
            this.balance = "￥" + this.agentInfo.balance;
          }
        });
    },
    // 时间格式化
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    afterRead(file) {
      console.log(file);
      // this.filesList.push({url: file.content})
    },
    onCancel() {
      this.showPopup = false;
    },
    onConfirm(value) {
      if (this.popupType == "payType") {
        this.selectedPayType = value;
      } else if (this.popupType == "date") {
        this.time = moment(value).format("YYYY年MM月DD日");
        this.currentDate = value;
      }
      this.showPopup = false;
      // this.pageNumber = 1
      // this.allList = []

      // this.loading = false
      // this.finished = false
    }
  }
};
</script>

<style scoped>
.upload-proof {
  padding: 10px 15px;
  display: flex;
}

.upload-proof-text {
  /* padding-right: 10px; */
  color: #323233;
  width: 100px;
  text-align: left;
}

.tip {
  padding: 10px 15px;
  background-color: #fff;
}

.tip p {
  margin-bottom: 5px;
}
</style>